/* eslint-disable  @typescript-eslint/no-explicit-any */

import axios, {
    AxiosError,
    AxiosResponse,
    InternalAxiosRequestConfig,
    AxiosRequestConfig,
} from 'axios';
import { ElMessage } from 'element-plus';

import { getMessageInfo } from './status';
import { getToken } from '@/utils/auth';
import { tansParams } from '@/utils';
import cache from '@/plugins/cache';

export interface BaseResponse<T = any> {
    code: number | string;
    message: string;
    data: T;
    status?: number;
}
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_DEV_USE_MOCK
        ? import.meta.env.VITE_APP_MOCK_BASEURL
        : import.meta.env.VITE_APP_API_BASEURL,
    timeout: 15000,
});

// 请求-拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // get请求映射params参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?' + tansParams(config.params);
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        const isToken = config.headers?.isToken === false;
        // 是否需要防止数据重复提交
        const isRepeatSubmit = config.headers?.repeatSubmit === false;
        console.log('🚀 ~ isRepeatSubmit:', isRepeatSubmit);
        console.log('🚀 ~ isToken:', isToken);
        if (getToken() && !isToken) {
            config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        if (
            !isRepeatSubmit &&
            (config.method === 'post' || config.method === 'put')
        ) {
            const requestObj = {
                url: config.url,
                data:
                    typeof config.data === 'object'
                        ? JSON.stringify(config.data)
                        : config.data,
                time: new Date().getTime(),
            };
            const sessionObj = cache.session.getJSON('sessionObj');
            if (
                sessionObj === undefined ||
                sessionObj === null ||
                sessionObj === ''
            ) {
                cache.session.setJSON('sessionObj', requestObj);
            } else {
                const s_url = sessionObj.url; // 请求地址
                const s_data = sessionObj.data; // 请求数据
                const s_time = sessionObj.time; // 请求时间
                const interval = 500; // 间隔时间(ms)，小于此时间视为重复提交
                if (
                    s_data === requestObj.data &&
                    requestObj.time - s_time < interval &&
                    s_url === requestObj.url
                ) {
                    const message = '数据正在处理，请勿重复提交';
                    console.warn(`[${s_url}]: ` + message);
                    return Promise.reject(new Error(message));
                } else {
                    cache.session.setJSON('sessionObj', requestObj);
                }
            }
        }
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    },
);

// 响应-拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response;
        }
        ElMessage({
            message: getMessageInfo(response.status),
            type: 'error',
        });
        return response;
    },
    (err: any) => {
        const { response } = err;
        if (response) {
            ElMessage({
                message: getMessageInfo(response.status),
                type: 'error',
            });
            return Promise.reject(response.data);
        }
        ElMessage({
            message: '网络连接异常，请稍后再试!',
            type: 'error',
        });
    },
);

// 二次拦截，为响应数据定制化处理
export const requestInstance = <T = any>(
    config: AxiosRequestConfig,
): Promise<BaseResponse<T>> => {
    const conf = config;
    return new Promise((resolve, reject) => {
        service
            .request<any, AxiosResponse<BaseResponse>>(conf)
            .then((res: AxiosResponse<BaseResponse>) => {
                const data = res.data;
                // 如果data.code为错误代码返回message信息
                if (data.code !== 0) {
                    ElMessage({
                        message: data.message,
                        type: 'error',
                    });
                    reject(data.message);
                } else {
                    ElMessage({
                        message: data.message,
                        type: 'success',
                    });
                    // 此处返回data信息 也就是 api 中配置好的 Response类型
                    resolve(data as BaseResponse<T>);
                }
            });
    });
};

export default service;
